#include <uci.h>
#include "data_type.h"
#include "idc_ubus.h"
#include "ep_gpio.h"
#include "lora_service.h"
#include "hash_map.h"

#define UCI_CONFIG_FILE "/etc/config/idc_energy"
#define NUM_THREADS             6

t_RunCfg runCfg;
pShartData ubus_cmd_Psd;
HashMap *online_devs;

void idc_load_config();

void init(){
    online_devs = map_create(INITIAL_CAPACITY);
    if (!online_devs) {
        printf("❌ 创建Map失败\n");
        return;
    }
    map_print_status(online_devs);

    idc_load_config();
    // ep_gpio_export(448);
    // ep_gpio_direction(448,2);
    sem_init(&ubus_cmd_Psd.sem, 0, 0);
    pthread_mutex_init(&ubus_cmd_Psd.mutex, NULL);
}
int main(int argc, char* argv[])
{
    init();
    pthread_t th_ubus;
    pthread_create(&th_ubus, NULL, (void*)ubus_worker, NULL);
    lora_worker_start();

    // ubus_invoke_get_lora_addr();
    while (true)
    {
        sleep(1);
    }
}


/*********************************************
* 载入配置文件,并遍历Section.
*/
void idc_load_config()
{
    struct uci_package * pkg = NULL;
    struct uci_element *e;
    struct uci_context * ctx = NULL;
    char *tmp;
    const char *value;

    ctx = uci_alloc_context(); // 申请一个UCI上下文.
    if (UCI_OK != uci_load(ctx, UCI_CONFIG_FILE, &pkg))
        goto cleanup; //如果打开UCI文件失败,则跳到末尾 清理 UCI 上下文.


    /*遍历UCI的每一个节*/
    uci_foreach_element(&pkg->sections, e)
    {
        struct uci_section *s = uci_to_section(e);

        printf("section s's type is %s.\n",s->type);
        if(!strcmp("conf",s->type)) //this section is a meter
        {
            /**MPPT配置**/
            if (NULL != (value = uci_lookup_option_string(ctx, s, "device")))
            {
                runCfg.device = strdup(value);
                printf("%s's device is %s.\n",s->e.name,value);
            }
            if (NULL != (value = uci_lookup_option_string(ctx, s, "speed")))
            {
                runCfg.speed = atoi(strdup(value));
                printf("%s's speed is %d.\n",s->e.name,runCfg.speed);
            }
            if (NULL != (value = uci_lookup_option_string(ctx, s, "is_center")))
            {
                printf("is_center:%s\n", strdup(value));
                runCfg.is_center = strdup(value);
            }
        }
    }
    uci_unload(ctx, pkg); // 释放 pkg
    cleanup:
    uci_free_context(ctx);
    ctx = NULL;
}

